﻿#region

using System;
using System.ComponentModel;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraTab;
using DevTools.ClassStuffGenerator.Components;
using DevTools.ClassStuffGenerator.Forms;
using DevTools.Properties;
using System.Linq;
#endregion

namespace DevTools.ClassStuffGenerator.Controls
{
    [DefaultEvent("SelectedTemplateChanged")]
    public partial class TemplateControl : XtraUserControl
    {
        private readonly int _templateIndex;

        public TemplateControl(int templateIndex)
        {
            InitializeComponent();

            _templateIndex = templateIndex;

            mmeFilter.Text = (string)Settings.Default["ClassStuffGenerator_Filter" + templateIndex];
            mmeTemplate.Text = (string)Settings.Default["ClassStuffGenerator_Template" + templateIndex];
        }

        public void WriteToTemplate()
        {
            Settings.Default["ClassStuffGenerator_Filter" + _templateIndex] = mmeFilter.Text;
            Settings.Default["ClassStuffGenerator_Template" + _templateIndex] = mmeTemplate.Text;
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            Generate();
        }

        public void Generate()
        {
            var items = ClassStuffGeneratorForm.Instance.GetItems();

            if (items.Count == 0)
                return;

            var filters = mmeFilter.Text.ToArray();

            var code = Generator.Generate(items, mmeTemplate.Text, filters);
            mmeCode.Text = code;

            if (string.IsNullOrEmpty(code))
                return;

            if (ClassStuffGeneratorForm.Instance.CopyToClipboardChecked)
                Clipboard.SetText(code);

            MainForm.Instance.NotifyMessage("코드를 생성하였습니다.");
        }

        private void btnAddAllTypes_Click(object sender, EventArgs e)
        {
            var items = ClassStuffGeneratorForm.Instance.GetItems();
            var array = (from x in items
                         orderby x.FieldName
                         select x.FieldName).Distinct();

            mmeFilter.Text += Environment.NewLine + string.Join(Environment.NewLine, array);
        }
    }
}